import '@unocss/reset/tailwind-compat.css';
import 'virtual:uno.css';

import './assets/main.scss';

import { createSSRApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import { createRouter } from './router';
import plugins from './plugins';
import { createI18n } from './i18n';
import lozad from '@/common/utils/lozad';
import {
  languageInjectionKey,
  communityInjectionKey,
  tokenInjectionKey,
  userAgentInjectionKey,
  // i18nInjectionKey,
  // storeInjectionKey,
} from './utils/keys';
import type { UserAgent } from '@/common/utils/user-agent';

export interface AppOptions {
  language: string,
  communityName: string,
  token: string,
  userAgent: UserAgent,
}

if (!import.meta.env.SSR) {
  const observer = lozad('.lozad', {
    enableAutoReload: true,
  });
  observer.observe();
}

export function createApp({ language, communityName, token, userAgent }: AppOptions) {
  const app = createSSRApp(App);

  app.provide(languageInjectionKey, language);
  app.provide(communityInjectionKey, communityName);
  app.provide(tokenInjectionKey, token);
  app.provide(userAgentInjectionKey, userAgent);

  const i18n = createI18n(language);
  app.use(i18n);
  // app.provide(i18nInjectionKey, i18n);

  const pinia = createPinia();
  app.use(pinia);
  // app.provide(storeInjectionKey, pinia);

  if (import.meta.env.SSR) {
    // 服务端处理
  }
  else {
    // 恢复状态
    if (window.__INITIAL_STATE__) {
      pinia.state.value = window.__INITIAL_STATE__;

      if (import.meta.env.DEV) {
        const prefetch = JSON.parse(JSON.stringify(window.__INITIAL_STATE__?.prefetch?.data ?? '{}'));

        console.groupCollapsed('%cSSR useAsyncData 调试数据', 'padding: 2px 6px; border-radius: 4px; color: #fff; background: #42c02e; font-weight: bold;');

        for (const key in prefetch) {
          if (prefetch[key]) {
            console.log(`%c${key}`, 'color: #3D7CFA;', prefetch[key]);
          }
        }

        console.groupEnd();
      }
    }
  }

  app.use(plugins);

  // 因为多语言的关系，路由一定要在 i18n 初始化后再初始化
  const router = createRouter({ pinia, i18n, language, communityName, token });
  app.use(router);

  return { app, router, pinia, i18n };
}
